package mediator;

import java.util.ArrayList;
import java.util.List;

public abstract class ChatParticipant
{
	protected String name;
	protected MessageMediator mediator;
	protected List<String> messageHistory = new ArrayList<>();

	public ChatParticipant(String name) {
		this.name = name;
	}

	public void joinChatroom(MessageMediator mediator) {
		this.mediator = mediator;
	}

	// 抽象方法：发送能力由子类决定
	public abstract boolean canSendText();
	public abstract boolean canSendImage();

	// 发送方法：检查权限后调用中介者
	public final void sendTextMessage(String receiverName, String content) {
		if (!canSendText()) {
			onSystemNotification("您没有发送文本消息的权限");
			return;
		}

		System.out.println("🔄 " + name + " 正在发送文本消息...");
		mediator.routeTextMessage(name, receiverName, content);
	}

	public final void sendImageMessage(String receiverName, String imageData) {
		if (!canSendImage()) {
			onSystemNotification("您没有发送图片的权限，请升级会员");
			return;
		}

		System.out.println("🔄 " + name + " 正在发送图片...");
		mediator.routeImageMessage(name, receiverName, imageData);
	}

	// 接收消息的处理方法
	public void onTextMessageReceived(String senderName, String content) {
		String record = String.format("[收到文本] %s: %s", senderName, content);
		messageHistory.add(record);

		displayTextNotification(senderName, content);
		handleIncomingTextMessage(senderName, content);
	}

	public void onImageMessageReceived(String senderName, String imageData) {
		String record = String.format("[收到图片] %s: %s", senderName, imageData);
		messageHistory.add(record);

		displayImageNotification(senderName, imageData);
		handleIncomingImageMessage(senderName, imageData);
	}

	public void onSystemNotification(String notification) {
		System.out.println("🔔 [系统通知 -> " + name + "] " + notification);
	}

	// 钩子方法：子类可重写以实现特殊逻辑
	protected void handleIncomingTextMessage(String senderName, String content) {}
	protected void handleIncomingImageMessage(String senderName, String imageData) {}

	// 显示方法：子类可重写以自定义显示
	protected void displayTextNotification(String senderName, String content) {
		System.out.println("💬 " + name + " 收到 " + senderName + " 的消息：" + content);
	}

	protected void displayImageNotification(String senderName, String imageData) {
		System.out.println("🖼️ " + name + " 收到 " + senderName + " 的图片：" + imageData);
	}

	// 工具方法
	public String getName() { return name; }
	public List<String> getMessageHistory() { return new ArrayList<>(messageHistory); }
}